package com.aischool.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.aischool.utils.StringUtil;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

public class SysUserAppService {

	public final String CK_CacheName = "CacheApp";
	public final String CK_Sys_User_App_Uid_Pre = "CK_Sys_User_App_Uid_";
	
	@Inject
	SysAppService sysAppService;
	
	/**
	 * 获取用户所属应用
	 * @param user_id
	 * @return
	 */
	public List<Record> getUserApp(int user_id){
		return Db.findByCache(CK_CacheName, CK_Sys_User_App_Uid_Pre + user_id, "SELECT a.* FROM sys_user_app a INNER JOIN sys_app b ON b.app_id = a.app_id WHERE b.app_state = 1 AND a.user_id = ?", user_id);
	}
	
	/**
	 * 更新用户应用权限
	 * @param user_id
	 * @param request
	 * @return
	 */
	public int updateUserApp(int user_id, HttpServletRequest request) {
		int ir = 0;
		int app_id = 0;
		String result = "";
		String ids_del = "";
		List<Record> listapp = sysAppService.getSysAppAll();
		for(int r=0;r<listapp.size();r++) {
			app_id = listapp.get(r).getInt("app_id");
			result = request.getParameter("app_id_" + app_id);
			if (result != null && !"".equals(result)) {
				ir += Db.update("INSERT INTO sys_user_app VALUES(?, ?) ON CONFLICT ON CONSTRAINT pk_sys_user_app DO NOTHING", 
						user_id, app_id);
			}else {
				ids_del += app_id + ",";
			}
		}
		if (ids_del.length()>0) {
			ir += Db.delete("DELETE FROM sys_user_app WHERE user_id = " + user_id + " AND app_id IN(" + StringUtil.trim(ids_del, ',') + ")");
		}
		if (ir>0) {
			CacheKit.remove(CK_CacheName, CK_Sys_User_App_Uid_Pre + user_id);
		}
		return ir;
	}
	
	public int setUserApp(int user_id, int app_id) {
		return Db.update("INSERT INTO sys_user_app VALUES(?, ?) ON CONFLICT ON CONSTRAINT pk_sys_user_app DO NOTHING", 
				user_id, app_id);
	}
	
	public void removeCache() {
		CacheKit.removeAll(CK_CacheName);
	}
}
